package houtai.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import houtai.mapper.LogMapper;
import houtai.pojo.Log;
import houtai.vo.LogVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class LogService {
    @Autowired
    private LogMapper logMapper;

    public LogVo queryLogs(Integer page, Integer pagesize, String sortProp, String sortOrder, String type, Long userId) throws ParseException {
        LogVo logVo = new LogVo();
        logVo.setPage(page);
        logVo.setPagesize(pagesize);

        QueryWrapper<Log> queryWrapper = new QueryWrapper<>();
        queryWrapper = queryWrapper.eq("user_id", userId);
        if (sortOrder.equals("ascending")) {
            queryWrapper = queryWrapper.orderByAsc(sortProp);
        }
        if (sortOrder.equals("descending")) {
            queryWrapper = queryWrapper.orderByDesc(sortProp);
        }
        List<Log> logList = logMapper.selectList(queryWrapper);

        if (CollUtil.isEmpty(logList)) {
            return logVo;
        }
        // 排除type之外的log
        logList.removeIf(log -> !log.getType().equals(type));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (Log log : logList) {
            String logTime = log.getLogTime();
            Date date = simpleDateFormat.parse(logTime);
            Long longDate = date.getTime();
            log.setLogTime(String.valueOf(longDate));
        }

        logVo.setPages(logList.size() / pagesize + 1);
        logVo.setCounts(logList.size());
        logVo.setItems(logList);

        return logVo;
    }
}